import _ from 'lodash'
import axios from '@/utils/axios'
import { getUserInfo } from 'api'

const USER = {
  LOGIN: 'LOGIN',
  SET_USER: 'SET_USER'
}

const initialState = {
  login: {
    show: false
  },
  user: {
    userName: '',
    unReadCount: 0
  }
}

const mutations = {
  [USER.LOGIN] (state, payload) {
    state.login = {
      ...state.login,
      ...payload
    }
  },
  [USER.SET_USER] (state, payload) {
    state.user = payload
  }
}

const actions = {
  getUserInfo ({ commit, dispatch }) {
    return new Promise(async (resolve, reject) => {
      try {
        const { ResultSet } = await axios.post(getUserInfo)
        dispatch('changeUserInfo', ResultSet.userData)
        resolve(ResultSet)
      } catch (err) {
        reject(err)
        // dispatch('changeLoginModal', { show: true, type: 'login', next, to })
        // this.$message.error(err.message || err.ResultSet.errors)
      }
    })
  },
  changeLogin ({ commit }, payload) {
    commit(USER.LOGIN, payload)
  },
  changeUserInfo ({ commit }, payload) {
    commit(USER.SET_USER, payload)
  },
  loadUserInfo ({ commit, dispatch }, {next, to, redirect}) {
    return new Promise(async (resolve, reject) => {
      try {
        const { ResultSet } = await axios.post(getUserInfo)
        if (ResultSet.userData.birth) ResultSet.userData.birth = parseInt(ResultSet.userData.birth.split('__DATE__')[1])
        localStorage.setItem('USERINFO', JSON.stringify(ResultSet.userData))
        dispatch('changeUserInfo', ResultSet.userData)
        resolve(ResultSet.userData)
        next({ path: redirect, replace: true })
      } catch (err) {
        console.log(err)
        // dispatch('changeLoginModal', { show: true, type: 'login', next, to })
        // this.$message.error(err.message || err.ResultSet.errors)
      }
    })
  },
  changeLogoConfig({ commit }, payload) {
    commit(USER.LOGO_CONFIG, payload)
  },
  loadLogoConfig({ commit, dispatch }) {
    return new Promise(async (resolve, reject) => {
      try {
        const { data } = await axios.get(logoConfig)
        dispatch('changeLogoConfig', data)
      } catch (err) {
        console.log(err)
      }
    })
  },
  changeShowNewTheme ({ commit }, payload) {
    commit(USER.SHOW_NEW_THEME, payload)
  }
}

const getters = {}

export default {
  state: _.cloneDeep(initialState),
  mutations,
  actions,
  getters
}
